package com.xl.singletonPattern.practice;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("🚦 比赛准备开始...");
        CountDownLatch startSignal = new CountDownLatch(1);    // 发令枪
        CountDownLatch finishSignal = new CountDownLatch(4);   // 4名运动员
        // 创建4个运动员线程
        for (int i = 1; i <= 4; i++) {
            final int runnerId = i;
            new Thread(() -> {
                try {
                    System.out.println("运动员 " + runnerId + " 就位，等待发令枪...");
                    startSignal.await(); // 等待发令枪响
                    System.out.println("运动员 " + runnerId + " 起跑！");
                    Thread.sleep(1000 + runnerId * 200); // 模拟跑步时间
                    System.out.println("运动员 " + runnerId + " 到达终点！");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    finishSignal.countDown(); // 报告完成
                    System.out.println("运动员 " + runnerId + " 报告完成");
                }
            }).start();
        }
        Thread.sleep(2000); // 裁判准备时间
        System.out.println("🔫 发令枪响！");
        startSignal.countDown(); // 发令枪响！
        System.out.println("裁判等待所有运动员完成...");
        finishSignal.await(); // 等待所有运动员完成
        System.out.println("🎉 所有运动员都完成了比赛！");
    }
}
